# -*- coding:utf-8 -*-
# @FileName : app\api\v1\conversations\services.py
# @Time     : 2025/11/28
# @Author   : 天空之城
"""
对话模块业务逻辑文件（已移除所有 AI 思考步骤 thought）

- 删除 thought 类型逻辑
- 删除步骤保存 _save_agent_execution_step
- Message 仅保留内容 + 工具调用记录，不再存储思考步骤
"""
import json
from typing import List, Dict, Any, Optional, Tuple
from datetime import datetime
from sqlalchemy.orm import joinedload

from app.models import Conversation, Message, User
from app.models.conversation import ConversationMode, ConversationStatus, MessageRole, MessageStatus
from app.services.agent_service import AgentService
from app.extensions import db
from app.config import logger


class ConversationService:
    """对话服务（保留正常功能，移除 thought）"""

    def __init__(self):
        self.agent_service = AgentService()

    def create_conversation(self, user_id: int, title: str = None,
                            mode: ConversationMode = ConversationMode.CHAT) -> Optional[Conversation]:
        """创建对话"""
        try:
            conversation = Conversation(
                user_id=user_id,
                title=title or f"新对话 {datetime.now().strftime('%Y-%m-%d %H:%M')}",
                mode=mode,
                status=ConversationStatus.IN_PROGRESS
            )
            db.session.add(conversation)
            db.session.commit()
            return conversation
        except Exception as e:
            db.session.rollback()
            logger.error(f"创建对话失败: {str(e)}")
            return None

    def get_conversation_by_id(self, conversation_id: int, user_id: int = None) -> Optional[Conversation]:
        """根据 ID 获取对话"""
        try:
            query = Conversation.query.options(joinedload(Conversation.messages))
            if user_id:
                query = query.filter(Conversation.user_id == user_id)
            conversation = query.filter(Conversation.id == conversation_id).first()
            return conversation
        except Exception as e:
            logger.error(f"获取对话失败: {str(e)}")
            return None

    def get_user_conversations(self, user_id: int, page: int = 1, per_page: int = 20):
        """获取用户所有对话"""
        try:
            pagination = Conversation.query.filter_by(user_id=user_id) \
                .order_by(Conversation.updated_at.desc()) \
                .paginate(page=page, per_page=per_page, error_out=False)

            return pagination.items, pagination.total
        except Exception as e:
            logger.error(f"获取用户对话失败: {str(e)}")
            return [], 0

    def update_conversation(self, conversation_id: int, user_id: int, **kwargs):
        """更新对话（移除 thought，不影响）"""
        try:
            conv = Conversation.query.filter_by(id=conversation_id, user_id=user_id).first()
            if not conv:
                return None

            updatable = ['title', 'status', 'meta_data']
            for field, val in kwargs.items():
                if field in updatable:
                    setattr(conv, field, val)

            conv.updated_at = datetime.utcnow()
            db.session.commit()
            return conv
        except Exception as e:
            db.session.rollback()
            logger.error(f"更新对话失败: {str(e)}")
            return None

    def delete_conversation(self, conversation_id: int, user_id: int) -> bool:
        """删除对话"""
        try:
            conv = Conversation.query.filter_by(id=conversation_id, user_id=user_id).first()
            if not conv:
                return False

            Message.query.filter_by(conversation_id=conversation_id).delete()
            db.session.delete(conv)
            db.session.commit()
            return True
        except Exception as e:
            db.session.rollback()
            logger.error(f"删除对话失败: {str(e)}")
            return False


class MessageService:
    """消息服务（已完全移除 thought 相关逻辑）"""

    def __init__(self):
        self.agent_service = AgentService()

    def create_message(self,
                       conversation_id: int,
                       role: MessageRole,
                       content: str,
                       tool_calls: Optional[List[Dict]] = None,
                       meta_data: Dict = None) -> Optional[Message]:
        """存储消息"""
        try:
            msg = Message(
                conversation_id=conversation_id,
                role=role.value,
                content=content,
                tool_calls=tool_calls,
                tool_results=None,
                status=MessageStatus.COMPLETED,
                meta_data=meta_data
            )
            db.session.add(msg)
            db.session.commit()
            return msg
        except Exception as e:
            db.session.rollback()
            logger.error(f"创建消息失败: {str(e)}")
            return None
    
    def create_message_with_steps(self, conversation_id: int, role: MessageRole,
                                 content: str, steps: List[Dict] = None):
        """创建包含执行步骤的消息"""
        try:
            meta_data = {"steps": steps} if steps else None
            
            msg = Message(
                conversation_id=conversation_id,
                role=role.value,
                content=content,
                status=MessageStatus.COMPLETED,
                meta_data=meta_data
            )
            db.session.add(msg)
            db.session.commit()
            return msg
        except Exception as e:
            db.session.rollback()
            logger.error(f"创建带步骤的消息失败: {str(e)}")
            return None

    def get_messages_by_conversation(self, conversation_id: int, limit: int = None):
        """获取对话消息"""
        try:
            query = Message.query.filter_by(conversation_id=conversation_id).order_by(Message.created_at.asc())
            if limit:
                query = query.limit(limit)
            msgs = query.all()
            return msgs
        except Exception as e:
            logger.error(f"获取消息失败: {str(e)}")
            return []

    def save_user_message(self, conversation_id: int, content: str, user_id: int = None):
        """
        ⚠️ 该方法目前不再使用（因为你在 routes 中直接调用 AgentService）
        但保留基本功能：保存消息 + 调用 Agent
        """
        try:
            conversation = Conversation.query.filter_by(id=conversation_id).first()
            if not conversation:
                return False, None, "对话不存在"

            # 保存用户消息
            user_msg = self.create_message(
                conversation_id, MessageRole.USER, content
            )

            # ===== 已删除 thought 步骤 =====
            agent_result = self.agent_service.handle_user_message(
                conversation_id=str(conversation_id),
                user_input=content,
                history_messages=[]
            )

            ai_content = agent_result.get("message", {}).get("content", "（无内容）")
            ai_msg = self.create_message(
                conversation_id,
                MessageRole.ASSISTANT,
                ai_content,
                tool_calls=agent_result.get("tool_execution_logs", [])
            )

            conversation.updated_at = datetime.utcnow()
            db.session.commit()

            return True, ai_msg, ""

        except Exception as e:
            db.session.rollback()
            return False, None, f"处理用户消息失败: {str(e)}"
